package com.xinzhi.savingpot.util;

import com.xinzhi.savingpot.configure.GeneratorCodeConfig;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

//加载图片为Base64
@Component
public class ImageUtil {
    private BASE64Encoder encoder = new BASE64Encoder();
    private BASE64Decoder decoder = new BASE64Decoder();

    //   把图片转码为Base64格式的字符串返回
    public String ImageToBase64(String imgPath) throws IOException {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try{
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            System.out.println(data);
            in.read(data);
        }  catch (IOException e){
            e.printStackTrace();
        } finally {
            if (in != null) {in.close();}
        }
//        encoder.encode(data)  将字节转码为Base64格式的字符串，这里我直接返回了

        return "data:image/jpg;base64," + encoder.encode(data);//将图片链接传入方法，拿到Base64格式的字符串;
    }

    //  将base64格式的字符串转为图片保存到本地
    public void base64StringToImage(String base64String) {
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File f1 = new File("d://out.jpg");
            ImageIO.write(bi1, "jpg", f1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String image2Base64(String imgUrl) throws IOException {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return "data:image/jpg;base64," + encoder.encode(outStream.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(is != null) is.close();
            if(outStream != null) outStream.close();
            if(httpUrl != null) httpUrl.disconnect();
        }

        return imgUrl;
    }
}
